(function() {
  var Async, Fs, ImageHandle, Logger, Request, downloadTotal, _;

  Request = require('request');

  Async = require('async');

  _ = require('underscore');

  Fs = require('fs');

  Logger = require('log4js').getLogger();

  downloadTotal = 0;

  ImageHandle = (function() {

    function ImageHandle(options) {
      var defaults;
      defaults = {
        downloadLimit: 5
      };
      this.opts = _.extend(defaults, options);
    }

    ImageHandle.prototype.downloadImages = function(imageList) {
      var downloadLimit, opts, self;
      self = this;
      opts = self.opts;
      if (!_.isArray(imageList)) {
        return self;
      }
      downloadLimit = opts.downloadLimit;
      return Async.forEachLimit(imageList, downloadLimit, function(imgSrc, cbf) {
        var requestOpts;
        requestOpts = {
          url: imgSrc,
          encoding: null
        };
        return Request(requestOpts, function(err, res, data) {
          if (err) {
            Logger.error(err);
          } else {
            console.log("isBuffer" + (Buffer.isBuffer(data)));
            Fs.writeFile("/Users/vicanso/workspace/my_node/tmp/" + downloadTotal + ".jpg", data, 'binary');
            downloadTotal++;
          }
          return cbf();
        });
      }, function() {
        return console.log('finished');
      });
    };

    return ImageHandle;

  })();

  module.exports = ImageHandle;

}).call(this);
